import bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "login")
public class login  implements Filter {

    public void init(FilterConfig filter) throws  ServletException{

    }
    public void destroy(){

    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filter) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse)res;
        HttpSession session = request.getSession(true);
        String token=request.getParameter("token");
        if(request.getServletPath().contains("index.jsp")||request.getServletPath().contains("register.jsp")||request.getServletPath().contains("error.jsp")||request.getServletPath().contains("register_success.jsp"))
        {
            filter.doFilter(req,res);
            return ;
        }
        if(token!=null) session.setAttribute("token",token);
        String user=(String)session.getAttribute("token");
        User name1=(User)request.getSession().getAttribute("user");
        if(user== null&&name1==null){
            response.sendRedirect("index.jsp");
        }
        else filter.doFilter(req,res);
    }
}
